-- LuaTools需要PROJECT和VERSION这两个信息
PROJECT = "wifidemo"
VERSION = "1.0.0"

-- 引入必要的库文件(lua编写), 内部库不需要require
sys = require("sys")
require("sysplus")

-- sys.subscribe("WLAN_READY", function ()
--     print("!!! wlan ready event !!!")
-- end)

-- sys.taskInit(function()
--     while 1 do
--         sys.wait(5000)
--         log.info("lua", rtos.meminfo())
--         log.info("sys", rtos.meminfo("sys"))
--     end

-- end)

local LEDA= gpio.setup(7, 0, gpio.PULLUP)

-- 兼容V1001固件的
if http == nil and http2 then
    log.info("http", "use http2")
    http = http2
end

sys.taskInit(function()
    sys.wait(1000)
    wlan.init()
    wlan.connect("luatos_1234", "12345678") -- "luatos_1234", "12345678"
    log.info("wlan", "wait for IP_READY")
    sys.waitUntil("IP_READY", 30000)
    if wlan.ready() then
        log.info("wlan", "ready !!")
		
		local info = wlan.getInfo()
		log.info("wlan info", json.encode(info) )

        log.info("wlan staIp")

        wlan.staIp(false, "192.168.4.10")

        log.info("wlan getIP", wlan.getIP() )

        -- 建立 httpsrv
        httpsrv.start(80, function(fd, method, uri, headers, body)
            log.info("httpsrv 收到了信息", method, uri, json.encode(headers), body)
            log.info("httpsrv 收到了信息", fd)
            if uri == "/led/1" then
                LEDA(1)
                return 200, {}, "ok"
            elseif uri == "/led/0" then
                LEDA(0)
                return 200, {}, "ok"
            end

            return 200, {} , "ok"
        end)

        sys.wait(100)
        local onLedUrl = "http://192.168.4.1/led/1"
        local offLedUrl = "http://192.168.4.1/led/0"
        local len = 1
        while 1 do
            sys.wait(4000)
            onFlag = onFlag == 1 and 0 or 1
            url = onFlag == 1 and onLedUrl or offLedUrl 
            log.info("url", url)
            local code, headers, body = http.request("GET", url).wait()
            -- log.info("http", code, json.encode(headers or {}), body and #body or 0)
            if body and #body < 512 then
                --     log.info("body", body)
            end
        end
        
    else
        print("wlan NOT ready!!!!")
    end
    log.info("wlan", "test done")
end)

-- 用户代码已结束---------------------------------------------
-- 结尾总是这一句
sys.run()
-- sys.run()之后后面不要加任何语句!!!!!
